package com.kamisama.utopia.assembler;

import com.kamisama.utopia.dto.OpenIdDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;

@Component
@Slf4j
public class WeChatAssembler {

    @Value("${wechat.code2Session.url}")
    private String code2SessionUrl;

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String secret;

    @Autowired
    private RestTemplate restTemplate;

    public OpenIdDto getOpenId(String jscode) {
        try {
            OpenIdDto openIdDto = restTemplate.getForEntity(
                MessageFormat.format(code2SessionUrl, appId, secret, jscode), OpenIdDto.class).getBody();
            log.info("response from wechat with {}", openIdDto);
            return openIdDto;
        } catch (HttpStatusCodeException exception) {
            if (exception.getStatusCode().equals(HttpStatus.EXPECTATION_FAILED)) {
                return null;
            }
            throw exception;
        }
    }
}
